﻿using System;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;
using System.Threading;

namespace FCNS.KeepMoney
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("KeepMoney 更新 \\(^o^)/ \r\n");

            Process[] ps = Process.GetProcessesByName("KeepMoney");
            Console.WriteLine("正在结束 KeepMoney 实例进程..." + ps.Length);
            foreach (Process p in ps)
                p.Close();

            if (ps.Length > 0)
            {
                Console.Write("KeepMoney 实例进程无法结束，更新失败");
                return;
            }

            Console.WriteLine("开始更新...");

            ProcessStartInfo psi = new ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + "KeepMoney.exe");
            psi.Arguments = "Decompress";
            Process.Start(psi);

            System.Threading.Thread.Sleep(5000);
            Process[] ps2 = Process.GetProcessesByName("KeepMoney");
            while (ps2.Length > 0)
            {
                ps2 = Process.GetProcessesByName("KeepMoney");
            }

            try
            {
                pro_Exited(AppDomain.CurrentDomain.BaseDirectory + "update", AppDomain.CurrentDomain.BaseDirectory);
                Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + "update", true);
            }
            catch (Exception ee) { Console.WriteLine(ee.Message); }

            Console.WriteLine("更新完成  -_-|||   点击任意键退出。");
            Console.Read();
        }

        static void pro_Exited(string sourceDirName, string destDirName)
        {
            if (sourceDirName.Substring(sourceDirName.Length - 1) != "\\")
            {
                sourceDirName = sourceDirName + "\\";
            }
            if (destDirName.Substring(destDirName.Length - 1) != "\\")
            {
                destDirName = destDirName + "\\";
            }
            if (Directory.Exists(sourceDirName))
            {
                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                }
                foreach (string item in Directory.GetFiles(sourceDirName))
                {
                    File.Copy(item, destDirName + Path.GetFileName(item), true);
                }
                foreach (string item in Directory.GetDirectories(sourceDirName))
                {
                    Copy(item, destDirName + item.Substring(item.LastIndexOf("\\") + 1));
                }
            }
        }
    }
}
